import { useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';

//@ts-ignore
import { moneyFormat, nanoid10 } from '@/utils';
import { msgInfo } from '@/utils/msg';
import { Form, Popup } from 'devextreme-react';
import notify from 'devextreme/ui/notify';
import SubjectPopup from '~/public/cpas-business/components-bs/SubjectPopup';
import DevGrid from '~/public/cpas-ui/components-ui/express-components/DevGrid';
import DevToolBar from '~/public/cpas-ui/components-ui/express-components/DevToolBar';
import AccountingVoucherPupop from '../accountingEntryTest/rightTables/components/accountingVoucherPupop';
import PageLoading from '../components/PageLoading';
import '../DoubtChecking/index.less';
import { testColumns, testColumnsZY } from './const';
import { getSqlApiList } from './server';

const SummaryAnalyisi = () => {
  const { initialState } = useModel('@@initialState');
  const { dbname, sjxmbh, zcbfName, sjnd, XMType, bsdw } = initialState?.curPart;
  const { username } = initialState?.curUser as API.CurUser;
  const ztModel = useModel('ztModel');

  const { ztDates, dataList } = ztModel;
  const dd = dataList.filter((a: any) => a.Data_ID === sjnd);
  const [displaydataId, SetdisplaydataId] = useState<any>(
    dd.length ? dd[0].displayName : `[${sjnd}]${zcbfName}`,
  );
  const [Zylist, setZylist] = useState<any[]>();
  const [summary, setSummary] = useState<any[]>();
  const [isDis, setIsDis] = useState(true);
  const [isViewZY, setIsviewZY] = useState(false);
  const [subject, setSubject] = useState('');
  const SubjectRef = useRef<any>();
  const InputRef = useRef<any>();
  const KMBH = useRef<any>();
  const currentQuery = useRef<any>({ dataID: sjnd });
  const [dataId, setDataId] = useState(sjnd);
  const [startMouth, setStartMouth] = useState(`${sjnd}01`);
  const [endMouth, setEndMouth] = useState(`${sjnd}01`);
  const subjectRef = useRef<any>('');
  const startMouthRef = useRef<any>(`${sjnd}01`);
  const endMouthRef = useRef<any>(`${sjnd}01`);
  const Days = useRef([
    '全部',
    ...Array.from(new Array(12), (x, i) => (i <= 8 ? `${sjnd}0${i + 1}` : `${sjnd}${i + 1}`)),
  ]);
  const accountingVoucherPupopRef = useRef<any>(null);
  const [spinLoad, setSpinLoad] = useState(false);
  const employee = {
    摘要: summary?.length ? summary[0].ZY : '',
    发生笔数: summary?.length,
    凭证数: [...new Set(summary?.map((a: any) => a.PZBH))].length,
  };

  const toolbarItems = [
    {
      html: '<span style="font-weight:normal ;font-size: 14px;">账套: </span>',
      location: 'before',
      cssClass: 'yd-zt-select-label',
    },
    {
      widget: 'dxSelectBox',
      cssClass: 'yd-zt-select',
      options: {
        width: 240,
        items: dataList,
        // dataSource: { dataIds },
        value: displaydataId,
        // defaultValue: `[${sjnd}]${zcbfName}`,
        valueExpr: 'displayName',
        displayExpr: 'displayName',
        onItemClick: async (e: any) => {
          // [2019]北京东方雨虹防水技术股份有限公司2020年中报审计
          // dataSource={accountYearData}
          // displayExpr='displayName'
          // valueExpr='displayName'
          // defaultValue={selDefaultValue}
          currentQuery.current.dataID = e.itemData.Data_ID;
          setDataId(e.itemData.Data_ID);
          SetdisplaydataId(e.itemData.displayName);

          let date: string = await getMonthList(e.itemData.Data_ID);
          setIsDis(true);
          setSubject('');
        },
      },
      location: 'before',
    },

    {
      cssClass: 'yd-date',
      html: '<span style="font-weight:normal ;font-size: 14px;">月份</span>',
      location: 'before',
    },
    {
      widget: 'dxSelectBox',
      options: {
        width: 110,
        value: startMouth,
        items: Days.current,
        onItemClick: function (e: any) {
          // ...
          setStartMouth(e.itemData);
          startMouthRef.current = e.itemData;
          if (e.itemData === '全部') {
            setEndMouth('全部');
            endMouthRef.current = '全部';
          } else {
            if (endMouth === '全部' || Number(e.itemData) > Number(endMouth)) {
              setEndMouth(e.itemData);
              endMouthRef.current = e.itemData;
            }
          }
        },
      },
      location: 'before',
    },
    {
      html: '<span style="font-weight:normal ;font-size: 14px;">至</span>',
      location: 'before',
    },
    {
      widget: 'dxSelectBox',
      options: {
        width: 110,
        value: endMouth,
        items: Days.current,
        onItemClick: function (e: any) {
          // ...
          setEndMouth(e.itemData);
          endMouthRef.current = e.itemData;
          if (e.itemData === '全部') {
            setStartMouth('全部');
            startMouthRef.current = '全部';
          } else {
            if (startMouth === '全部' || Number(e.itemData) < Number(endMouth)) {
              setStartMouth(e.itemData);
              startMouthRef.current = e.itemData;
            }
          }
        },
      },
      location: 'before',
    },
    {
      widget: 'dxCheckBox',
      location: 'before',
      cssClass: 'yd-date',
      options: {
        text: '全部科目',
        value: isDis,
        onValueChanged: (e: any) => {
          setIsDis(!isDis);
          if (e.value) {
            setSubject('');
          }
        },
      },
    },
    {
      widget: 'dxButton',
      location: 'before',
      options: {
        text: '选择科目',
        disabled: isDis,
        onClick: () => {
          SubjectRef.current.show({
            title: '选择科目',
            dbname: dbname,
            Data_ID: dataId,
            isHasFZZ: false,
            editUser: username,
            // 选择 模式 0：单选 1：多选连机选择
            selectMode: '1',
            //  1：多选连机选择时是否进行递归选择默认是 true
            recursiveMultiple: false,
            // 是否为辅助账
            auxiliaryState: false,
            // 可以选择当前节点的科目
            isSelectSuperior: false,
            // 自动结转科目 默认选中的类型参数
            subjectType: 'periodEarly',
            okCallback: (r: any, v: any) => {
              // debugger;
              // r.KMBH
              KMBH.current = r.KMBH;
              setSubject(r.KMMC);
              subjectRef.current = r.KMMC;
            },
          });
        },
      },
    },
    {
      widget: 'dxTextBox',
      options: {
        readOnly: true,
        value: subject,
      },
      location: 'before',
    },
    {
      widget: 'dxButton',
      cssClass: 'yd-handle-button',
      options: {
        text: '分析',
        type: 'default',
        disabled: !startMouth?.length,
        onClick: async () => {
          // debugger;
          let p = {
            Data_ID: dataId,
            startMouth: `${startMouth}`,
            endMouth: `${endMouth}`,
          };
          if (subject !== '') {
            await getZylist(p, subject, KMBH.current);
          } else {
            await getZylist(p);
          }
          setSpinLoad(false);
        },
      },
      location: 'before',
    },
  ];
  useEffect(() => {
    let date = getMonthList(sjnd);
    // getDataids();
    // 一个月，
  }, []);
  useEffect(() => {
    ztModel.refresh();
  }, []);

  // const getDataids = async () => {
  //   const dd: any = await getSqlApiList('account.accountInfo.getDataList', { dbname: dbname });
  //   if (dd.data?.length) {
  //     //.sort((a: any, b: any) => a - b))
  //     setDataIds(dd.data);
  //   }
  // };

  const getMonthList = async (Data_ID: string) => {
    const dd: any = await getSqlApiList('account.accountInfo.getMonthList', {
      dbname: dbname,
      Data_ID: Data_ID,
    });
    if (dd.data?.length) {
      //
      let ddcosnt = dd.data.map((a: any) => a.YF).sort((a: any, b: any) => a - b);

      setEndMouth(ddcosnt[0]);
      setStartMouth(ddcosnt[0]);
      endMouthRef.current = ddcosnt[0];
      startMouthRef.current = ddcosnt[0];
      Days.current = ['全部', ...ddcosnt];
      await getZylist({
        Data_ID: Data_ID,
        startMouth: ddcosnt[0],
        endMouth: ddcosnt[0],
      });
      return ddcosnt[0];
    } else {
      endMouthRef.current = '';
      startMouthRef.current = '';
      setEndMouth('');
      setStartMouth('');
      Days.current = [];
      notify('凭证表没有数据，请重新转换数据', 'error', 2000);
    }
  };

  const getZylist = async (
    P: {
      Data_ID: string;
      startMouth?: string;
      endMouth?: string;
    },
    kmmc?: string,
    KMBH?: string,
  ) => {
    let par = {};
    let pardate = {};
    if (P.startMouth === '全部') {
      pardate = { ...P, startMouth: `${P.Data_ID}0101`, endMouth: `${P.Data_ID}1231` };
    } else if (P.startMouth) {
      pardate = { ...P, startMouth: `${P.startMouth}01`, endMouth: `${P.endMouth}31` };
    } else {
      // 首次进去一个月
      pardate = { ...P, startMouth: `${P.Data_ID}0101`, endMouth: `${P.Data_ID}0131` };
    }

    if (kmmc) {
      par = { ...pardate, kmmc: kmmc, kmbh: KMBH };
    } else {
      par = pardate;
    }
    // debugger;
    setSpinLoad(true);
    let d = await getSqlApiList('account.PZB.getAnalyisZylist', { ...par, dbname: dbname });
    setSpinLoad(false);

    if (d?.data?.length) {
      setZylist(d.data);
    } else {
      setZylist([]);
      notify('凭证表没有数据，请重新转换数据', 'error', 2000);
    }
  };

  const getOneZylist = async (P: {
    Data_ID: string;
    startMouth: string;
    summary: string;
    endMouth: string;
    subject: string;
  }) => {
    const subject = P.subject > '' ? `and (KMMC  = '${P.subject}%' )` : '';
    let d = await getSqlApiList('accountingEntryTest.customDefineQuery.getDataList', {
      dbname: dbname,
      Data_ID: P.Data_ID,
      displayOption: false,
      otherWhere: `and ZY = '${P.summary}'  and substring(pzrq,1,8) between '${P.startMouth}' and '${P.endMouth}' ${subject}`,
    });
    if (d.ok) {
      setSummary(
        d.data.map((a: any) => {
          return {
            PZRQ: a.PZRQ,
            PZBH: a.PZBH,
            PZLX: a.PZLX,
            FLID: a.FLID,
            YSKMBH: a.YSKMBH,
            KMMC: a.KMMC,
            ZY: a.ZY,
            JFJE: a.JFJE,
            DFJE: a.DFJE,
          };
        }),
      );
    } else {
      setSummary(d.data);
    }
  };

  /**
   *
   * @param e
   * @returns
   */
  const onClickRowDbZy = async ({ key }: any) => {
    // console.log(e)
    let dateStart = `${startMouthRef.current}01`;
    let dateEndMouth = `${endMouthRef.current}31`;
    if (startMouthRef.current === '全部') {
      dateStart = `${dataId}0101`;
      dateEndMouth = `${dataId}1231`;
    }
    await getOneZylist({
      Data_ID: dataId,
      startMouth: `${dateStart}`,
      endMouth: `${dateEndMouth}`,
      summary: key,
      subject: subjectRef.current,
    });
    setIsviewZY(true);
  };

  const onClickRowDbZylist = async ({ data }: any) => {
    let tmepRowData = [{ ...data, Data_ID: dataId, dbname }];
    // 对当前凭证编号进行唯一排序，点击时查找数字的上一个
    let arr = [...new Set(summary?.map((a: any) => a.PZBH))];
    let arr_list: any = [];
    if (arr.length > 1) {
      arr?.forEach((a: any) => {
        let d = summary?.filter((e: any) => e.PZBH === a && a !== data.PZBH);
        if (d?.length) {
          arr_list.push({
            PZBH: d[0].PZBH,
            PZLX: d[0].PZLX,
            PZRQ: d[0].PZRQ,
            FLID: d[0].FLID,
            Data_ID: dataId,
            dbname,
          });
        }
      });
      tmepRowData = [...tmepRowData, ...arr_list];
    }
    accountingVoucherPupopRef.current.showPupop({ ...data, Data_ID: sjnd, dbname }, tmepRowData);
  };

  const PopZy = useMemo(() => {
    return (
      <Popup
        ref={InputRef}
        height={'90vh'}
        width={'90vw'}
        title={'凭证浏览'}
        visible={isViewZY}
        onHiding={() => {
          setIsviewZY(false);
        }}
      >
        <div style={{ width: '100', height: '100%' }}>
          <Form
            formData={employee}
            readOnly={true}
            colCount={3}
            width={'500'}
            minColWidth={400}
            items={['摘要', '凭证数', '发生笔数']}
          >
            {/* <Item widget={'1'}></Item> */}
          </Form>
          <p></p>
          <DevGrid.RangeTap
            key={nanoid10()}
            dataSource={summary}
            keyExpr="ZY"
            paging={{
              pageSize: 0,
            }}
            height={'90%'}
            id={'yd-right-grid'}
            ContextMenu={contextMenu}
            excelName="凭证浏览"
            defaultColumns={testColumnsZY}
            scrolling={{
              mode: 'virtual',
              renderAsync: true,
              rowRenderingMode: 'virtual',
            }}
            showBorders={true}
            summary={{
              totalItems: [
                {
                  column: 'PZRQ',
                  customizeText: (a: any) => `总计：${a.value}`,
                  summaryType: 'count',
                  cssClass: 'zyfontColor',
                },
                {
                  column: 'DFJE',
                  summaryType: 'sum',
                  name: 'ww',
                  // caption: '贷方比重(%)',
                  skipEmptyValues: true,
                  // valueFormat: 'currency',
                  customizeText: (a: any) => moneyFormat(Number(a.value)),
                  cssClass: 'zyfontColor',
                },

                {
                  column: 'JFJE',
                  summaryType: 'sum',
                  customizeText: (a: any) => moneyFormat(Number(a.value)),
                  cssClass: 'zyfontColor',
                },
              ],
            }}
            onRowDblClick={onClickRowDbZylist}
          />
        </div>
      </Popup>
    );
  }, [summary, isViewZY]);
  const RightTable = useMemo(() => {
    debugger;
    return (
      <DevGrid.RangeTap
        key={nanoid10()}
        dataSource={Zylist}
        keyExpr="zy"
        id={'yd-right-grid'}
        ContextMenu={contextMenu}
        defaultColumns={testColumns}
        showBorders={true}
        width={'100%'}
        excelName="摘要汇总分析"
        scrolling={{
          mode: 'virtual',
          renderAsync: true,
          rowRenderingMode: 'virtual',
        }}
        paging={{
          pageSize: 0,
        }}
        summary={{
          totalItems: [
            {
              column: 'zy',
              customizeText: (a: any) => `总计：${a.value}`,
              summaryType: 'count',
              cssClass: 'zyfontColor',
            },
            {
              column: 'realJfje',
              summaryType: 'sum',
              name: 'ww',
              // caption: '贷方比重(%)',
              skipEmptyValues: true,
              // valueFormat: 'currency',
              customizeText: (a: any) => moneyFormat(Number(a.value)),
              cssClass: 'zyfontColor',
            },
            {
              column: 'strJfbz',
              summaryType: 'sum',
              customizeText: (a: any) => `${Number(a.value).toFixed(2)}`,
              cssClass: 'zyfontColor',
            },
            {
              column: 'realDfje',
              summaryType: 'sum',
              customizeText: (a: any) => moneyFormat(Number(a.value)),
              cssClass: 'zyfontColor',
            },
            {
              column: 'strDfbz',
              summaryType: 'sum',
              customizeText: (a: any) => `${Number(a.value).toFixed(2)}`,
              cssClass: 'zyfontColor',
            },
          ],
        }}
        onRowDblClick={onClickRowDbZy}
      />
    );
  }, [Zylist]);

  function contextMenu(e: any) {
    const { column, row, columnIndex, rowIndex } = e;
    const { dataField, dataType } = column;
    const defaultMenu = [
      {
        text: '添加自定义菜单选项',
        onItemClick: () => {
          alert(dataField);
        },
      },
    ];
    return defaultMenu;
  }
  return (
    <>
      <SubjectPopup ref={SubjectRef} />
      <PageLoading isOpen={spinLoad} isMaskClose={false} content={'正在加载...'} width={200} />
      <AccountingVoucherPupop
        ref={accountingVoucherPupopRef}
        cellDblClickCallback={(rowData: any, curYear: any) => {
          msgInfo(`正在打开 明细账,请稍候...`);
          if (window.electronComponents) {
            const sessionParams = JSON.parse(window.sessionStorage.electronParams);
            const { sjxmbh, ZcbfID } = sessionParams.params;
            window.location.href = `cpas://OpenLocalFile/?fileName={UFCPAS4_PATH}/UFCPAS4.exe&params=UserCode={UserCode} UserPwd={UserPwd} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID} Functions=FM_103 FunParameters="Data_ID=${curYear},KMBH=${rowData.KMBH}"`;
          } else {
            console.error('window["electronComponents"] false');
          }
        }}
      />
      {PopZy}
      <div style={{ height: '85vh' }}>
        <DevToolBar.Default items={toolbarItems} style={{ padding: '8px 0' }} />
        {/* <span>摘要汇总结果，共有汇总项： {Zylist?.length}</span> */}
        {RightTable}
      </div>
    </>
  );
};

export default SummaryAnalyisi;
